#!/usr/bin/python
#coding:utf8
'''
Memento
'''
import copy
# 备忘录类用于保存对象的状态
class Memento:
    def __init__(self, state):
        self._state = state

    def get_state(self):
        return self._state

# 文本编辑类
class TextEditor:
    def __init__(self):
        self.content = []

    def type(self, s):
        self.content.append(s)
    
    # 这里要注意，保存的是当前对象的一个深拷贝，而不是引用
    def save(self):
        return Memento(copy.deepcopy(self.content))

    def restore(self, memento):
        self.content = memento.get_state()

# 管理者类用于管理备忘录
class CareTaker:
    def __init__(self):
        self.mementos = []

    def save(self, memento):
        self.mementos.append(memento)

    def undo(self):
        if len(self.mementos) > 0:
            memento = self.mementos.pop()
            return memento
        else:
            return None
    
    def getMemento(self, index):
        return self.mementos[index]

if __name__ == '__main__':
    editor = TextEditor()
    taker = CareTaker()
    editor.type('hello')
    taker.save(editor.save())
    editor.type('world')
    taker.save(editor.save())
    memento = taker.getMemento(0)
    print(f"回到第一次键入的状态：{memento.get_state()}")
    memento = taker.getMemento(1)
    print(f"回到第二次键入的状态：{memento.get_state()}")
